package com.mc.string;
import java.util.Scanner;

public class TicTacToe {
	
	private String player1;
	private String player2;
	private int[][] matrix = new int[3][3];
	private int count=0;
	public void run(){
		Scanner input = new Scanner(System.in);
		System.out.println("Welcome to Tic Tac Toe!");
		System.out.println();
		System.out.println("Enter Player O's name:");
		player1 = input.next();
		System.out.println("Enter Player X's name:");
		player2 = input.next();
		printGrid();
		int turn = 1;
		while(count!=9){
			if(turn==1){
				System.out.println(player1+"'s move:");
				int x1 = input.nextInt();
				int y1 = input.nextInt();
				matrix[x1][y1]=1;
				printGrid();
				turn=2;
				if(getGameState(x1,y1)==1){
					System.out.println("Game over. "+player1+" won!");
					return;
				}
			}
			else{
				System.out.println(player2+"'s move:");
				int x2 = input.nextInt();
				int y2 = input.nextInt();
				matrix[x2][y2]=2;
				printGrid();
				turn=1;
				if(getGameState(x2,y2)==1){
					System.out.println("Game over. "+player2+" won!");
					return;
				}
			}
			count++;
		}
		if(count==9)	
			System.out.println("Game over. It was a draw!");
	}
	private void printGrid(){
		for(int i = 0;i<3;i++){
			for(int j=0;j<3;j++){
				if(matrix[i][j]==0){
					System.out.print(" ");
				}
				else if(matrix[i][j]==1){
					System.out.print("O");
				}
				else{
					System.out.print("X");
				}
				if(j!=2)
					System.out.print("|");
				else
					System.out.println();
			}
			if(i!=2)
				System.out.println("-----");
		}
	}
	private int getGameState(int i,int j){
		if(row(i)!=0||column(j)!=0||diagonal(i,j)!=0||anti_diagonal(i,j)!=0){
			return 1;
		}
		return 0;
			
	}
	private int row(int i){
		int flag = matrix[i][0];
		for(int x = 1; x<3;x++){
			if(matrix[i][x]!=flag)
				return 0;
		}
		return flag;
	}
	private int column(int j){
		int flag = matrix[0][j];
		for(int x = 1; x<3;x++){
			if(matrix[x][j]!=flag)
				return 0;
		}
		return flag;
	}
	private int diagonal(int i, int j){
		if(i==j){
			int flag = matrix[0][0];
			for(int x = 1 ;x<3;x++){
				if(matrix[x][x]!=flag)
					return 0;
			}
			return flag;
		}
		return 0;
	}
	private int anti_diagonal(int i,int j){
		if(Math.abs(i-j)==2){
			int flag = matrix[0][2];
			int x=1;
			int y=1;
			while(x<3){
				if(matrix[x][y]!=flag)
					return 0;
				x++;
				y--;
			}
			return flag;
		}
		return 0;
	}
	public static void main(String[] args) {
		TicTacToe game = new TicTacToe();
		game.run();
	}
}
